package org.dreamwork.jasmine2.web.controls;

import org.dreamwork.jasmine2.configure.JasmineConfig;
import org.dreamwork.jasmine2.engine.HttpContext;
import org.dreamwork.jasmine2.i18n.I18nUtil;
import org.dreamwork.jasmine2.web.IWebControl;
import org.dreamwork.jasmine2.events.EventException;
import org.dreamwork.util.StringUtil;

import java.io.PrintWriter;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-7-23
 * Time: 11:39:52
 */
public class ListItem extends WebContainer {
    private String value, text;
    private boolean selected = false;

    public String getValue () {
        return value;
    }

    public void setValue (String value) {
        this.value = value;
        setAttribute ("value", value);
    }

    public String getText () {
        return text;
    }

    public void setText (String text) {
        this.text = text;
    }

    public boolean isSelected () {
        return selected;
    }

    public void setSelected (boolean selected) {
        this.selected = selected;
    }

    public void init () {
        super.init ();
        htmlTagName = "option";
    }

    public void addControl (IWebControl control) {
        if (control.getClass () != Literal.class)
            throw new IllegalArgumentException (control.getClass ().getName ());
        Literal literal = (Literal) control;
        this.setText (literal.text == null ? "" : literal.text.toString ());
    }

    @Override
    public void onPrerender (IWebControl sender, HttpContext context) throws EventException {
        super.onPrerender (sender, context);
        if (!StringUtil.isEmpty (text)) {
             if (context.getApplication ().getAttribute (JasmineConfig.JASMINE_I18N_HOLDER) != null)
                text = I18nUtil.eval (text, this);
            text = I18nUtil.escapeI18n (text);
        }
    }

    public void render (PrintWriter writer) throws IOException, EventException {
        writer.write ("<option");
        renderAttributes (writer);
        if (selected) writer.write (" selected=\"selected\"");
        writer.println (">" + text + "</option>");
    }
}